import React, {Component} from 'react';
import {View, StyleSheet, Linking} from 'react-native';
import NetInfo from '@react-native-community/netinfo';
import RNExitApp from 'react-native-exit-app';
import {Modal} from '@ant-design/react-native';
import Geolocation from '~/utils/geolocation';
import store from '~/store';
import {saveUserInfo} from '~/store/userinfo';
import {saveSystem} from '~/store/system';
import {getHttpUrl} from '~/api/basic';
import {getSysVersion} from '~/api/system';
import {getCityListOfOpen, getPopularCityListOfOpen} from '~/api/public';
import {checkUnreadMsgCount, resetMsgTimer} from '~/utils/backrun';

export default class Start extends Component {
    static navigationOptions = {
        headerTransparent: true,
    };

    constructor(props) {
        super(props);
        this.checkNetwork();
    }

    openUrl = () => {
        let url = 'http://www.yfdmcw.com/download.html?platform=' + global.AppData.platform + '&id=' + global.AppData.versionName;
        Linking.openURL(url).then(() => {
            RNExitApp.exitApp();
        });
    };

    checkNetwork = () => {
        NetInfo.fetch().then((state) => {
            if (state.isConnected) {
                this.checkVersion();
            } else {
                setTimeout(() => {
                    this.checkNetwork();
                }, 1000);
            }
        });
    };

    checkVersion = async () => {
        let data = {platform: global.AppData.platform, identity: global.AppData.versionName};
        let res = await getSysVersion(data);
        if (res.code === 0) {
            if (res.data !== null) {
                if (global.AppData.version < res.data.VerLowest) {
                    Modal.alert('错误', '当前版本过低，请立即更新！', [
                        {
                            text: '确定',
                            style: {
                                color: 'red',
                            },
                            onPress: () => {
                                this.openUrl();
                            },
                        },
                    ]);
                } else if (global.AppData.version < res.data.VerWarn) {
                    Modal.alert('警告', '当前版本过低，是否更新？', [
                        {
                            text: '确定',
                            style: {
                                color: 'red',
                            },
                            onPress: () => {
                                this.openUrl();
                            },
                        },
                        {
                            text: '暂不更新',
                            onPress: () => {
                                this.getBaseUrl();
                            },
                        },
                    ]);
                } else if (global.AppData.version < res.data.VerHighest) {
                    Modal.alert('提示', '发现新版本，是否更新？', [
                        {
                            text: '确定',
                            style: {
                                color: 'red',
                            },
                            onPress: () => {
                                this.openUrl();
                            },
                        },
                        {
                            text: '暂不更新',
                            onPress: () => {
                                this.getBaseUrl();
                            },
                        },
                    ]);
                } else {
                    this.getBaseUrl();
                }
            } else {
                Modal.alert('错误', '无法识别的版本，请重新安装！', [
                    {
                        text: '确定',
                        style: {
                            color: 'red',
                        },
                        onPress: () => {
                            this.openUrl();
                        },
                    },
                ]);
            }
        } else {
            Modal.alert('错误', '无法访问服务器，请检查网络是否正常', [
                {
                    text: '确定',
                    onPress: () => {
                        RNExitApp.exitApp();
                    },
                },
            ]);
        }
    };

    getBaseUrl = () => {
        getHttpUrl().then((res) => {
            if (res.code === 0) {
                global.AppData.base_url = res.data + '/';
                this.initCityData();
            }
        });
    };

    initCityData = async () => {
        await getPopularCityListOfOpen().then((r) => {
            if (r.code === 0) {
                store.dispatch(saveSystem({popular_city: r.data}));
            }
        });
        await getCityListOfOpen().then((r) => {
            if (r.code === 0) {
                let city_list = [];
                let temp_list = [];
                let letter = '';
                r.data.forEach((item) => {
                    if (item.FirstLetter !== letter) {
                        if (letter !== '') {
                            city_list.push({
                                letter: letter,
                                list: temp_list,
                            });
                        }
                        letter = item.FirstLetter;
                        temp_list = [];
                    }
                    temp_list.push(item);
                });
                city_list.push({
                    letter: letter,
                    list: temp_list,
                });
                store.dispatch(saveSystem({city_list}));
            }
        });
        this.setIdentity();
    };

    setIdentity = async () => {
        let identity = 0;
        let identitycode = '';
        switch (global.AppData.versionName) {
            case 'owner':
                identity = 8;
                identitycode = 'k3c9ww4li';
                break;
            case 'company':
                identity = 11;
                identitycode = 'kfwe93ls';
                break;
            case 'bank':
                identity = 21;
                identitycode = 'i3ddv56as';
                break;
            case 'agent':
                identity = 31;
                identitycode = 'r2fnje02b';
                break;
        }
        if (global.AppData.versionName !== 'dev') {
            store.dispatch(
                saveUserInfo({
                    identity,
                    identitycode,
                }),
            );
        }

        const getter = store.getState();
        if (getter.userinfo.userid > 0) {
            checkUnreadMsgCount();
        } else {
            resetMsgTimer();
        }

        await Geolocation(global.AppData.versionName);
        this.props.navigation.replace('Ads');
    };

    render() {
        return <View style={StyleSheet.absoluteFill} />;
    }
}
